package com.zhanglinwei.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

public final class RequestIdUtils {

    public static final String REQUEST_ID_HEADER_KEY = "X-APP-REQUEST-ID";

    private RequestIdUtils(){}

    public static String getRequestId() {
        return MDC.get(REQUEST_ID_HEADER_KEY);
    }

    public static void setRequestId(HttpServletRequest request) {
        String headerRequestId = request.getHeader(REQUEST_ID_HEADER_KEY);
        String requestId = StringUtils.isBlank(headerRequestId) ? generateRequestId() : headerRequestId;
        MDC.put(REQUEST_ID_HEADER_KEY, requestId);
    }

    public static String generateRequestId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void clear() {
        MDC.clear();
    }
}
